// SPDX-License-Identifier: Mulan PSL v2
/*
 * Copyright (c) 2025 Huawei Technologies Co., Ltd.
 * This software is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *         http://license.coscl.org.cn/MulanPSL2
 *
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

//! 请求记录模块
//! 
//! 该模块提供了记录和重放IPC通信中Request消息的功能，
//! 主要用于调试、性能分析和回归测试。

use std::path::PathBuf;
use std::time::Instant;
use std::collections::VecDeque;
use std::sync::atomic::{AtomicU64, Ordering};
use thiserror::Error;

pub mod format;
pub mod logger;
pub mod player;
pub mod proto_types;

#[cfg(test)]
mod tests;

/// 记录器错误类型
#[derive(Debug, Error)]
pub enum RecorderError {
    #[error("I/O error: {0}")]
    Io(#[from] std::io::Error),
    
    #[error("serialization error: {0}")]
    Serialization(String),
    
    #[error("deserialization error: {0}")]
    Deserialization(String),
    
    #[error("file format error: {message}")]
    FormatError { message: String },
    
    #[error("buffer overflow: required {required}, available {available}")]
    BufferOverflow { required: usize, available: usize },
    
    #[error("invalid record at position {position}")]
    InvalidRecord { position: u64 },
    
    #[error("protobuf encoding error: {0}")]
    ProtobufEncoding(#[from] prost::EncodeError),
    
    #[error("protobuf decoding error: {0}")]
    ProtobufDecoding(#[from] prost::DecodeError),
    
    #[error("file corruption detected: {details}")]
    Corruption { details: String },
}

/// 记录器配置
#[derive(Debug, Clone)]
pub struct RecorderConfig {
    /// 输出文件路径
    pub output_path: PathBuf,
    /// 文件格式
    pub format: RecordFormat,
    /// 是否启用压缩
    pub compression: bool,
    /// 缓冲区大小
    pub buffer_size: usize,
    /// 最大文件大小（字节）
    pub max_file_size: u64,
    /// 是否自动轮转文件
    pub auto_rotate: bool,
}

impl Default for RecorderConfig {
    fn default() -> Self {
        Self {
            output_path: PathBuf::from("requests.log"),
            format: RecordFormat::Protobuf,
            compression: false,
            buffer_size: 8192,
            max_file_size: 100 * 1024 * 1024, // 100MB
            auto_rotate: true,
        }
    }
}

/// 记录文件格式
#[derive(Debug, Clone, Copy)]
pub enum RecordFormat {
    /// Protobuf二进制格式
    Protobuf,
    /// JSON格式
    Json,
}

/// 记录器统计信息
#[derive(Debug, Default)]
pub struct RecorderStats {
    /// 记录的请求总数
    pub total_requests: u64,
    /// 写入的总字节数
    pub total_bytes: u64,
    /// 刷新次数
    pub flush_count: u64,
    /// 最后刷新时间
    pub last_flush: Option<Instant>,
}

// 重新导出主要类型
pub use logger::RequestLogger;
pub use player::RequestPlayer;
pub use format::{RecordWriter, RecordReader};